package com.zg.ktcomwan.fragment

import android.app.ProgressDialog
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.zg.core.ext.logI
import com.zg.ktcomwan.R
import com.zg.ktcomwan.adapter.ArticleAdapter
import com.zg.ktcomwan.base.BaseFragment
import com.zg.ktcomwan.databinding.ErrorLayoutBinding
import com.zg.ktcomwan.ext.toast
import com.zg.ktcomwan.vm.NetViewModel
import kotlinx.android.synthetic.main.fragment_article.*
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

/***
 * @Author:      zxd
 * @CreateDate:  2021/7/6 16:24
 * @Description:
 * 1.使用paging3，创建adapter
 * 2.抽取一个公共的list列表
 * https://blog.csdn.net/vitaviva/article/details/109400331
 * 3.paging3  https://juejin.cn/post/6952142358896967694    https://github.com/HyejeanMOON/Paging3Demo
 *
 */
class ListFragment : BaseFragment() {

    private val netViewModel: NetViewModel by viewModels()

    override fun getLayoutId(): Int {
        return R.layout.fragment_article
    }

    override fun afterCreate() {
        rv.layoutManager = LinearLayoutManager(activity)
        val adapter = activity?.let { ArticleAdapter(it) }
        rv.adapter = adapter

        lifecycleScope.launch {
            netViewModel.articleList.collectLatest {
                adapter!!.submitData(it)
            }
            /*netViewModel.articleList.collect{
                adapter!!.submitData(it)
            }*/
        }

        //addState(adapter)

        srl.setEnableRefresh(true)
        srl.setOnRefreshListener {
            adapter!!.notifyDataSetChanged()
            srl.finishRefresh(true)
        }
    }

    fun addState(adapter: ArticleAdapter?) {
        //打开界面，加载数据的时候显示loading，如果出数据了，那么隐藏掉对话框
        val dialog = ProgressDialog(activity)
        dialog.setTitle("Loading......")
        dialog.setMessage("等待中...")
        dialog.isIndeterminate = true
        dialog.setCancelable(false)
        adapter!!.addLoadStateListener {
            when (it.source.refresh) {
                //数据加载中。
                is LoadState.Loading -> {
                    dialog.show()
                    logI("Loading: ---------------------")
                }
                //内存中有已经获取的数据，即使往下滑，Paging 也不需要请求更多的数据。
                is LoadState.NotLoading -> {
                    dialog.cancel()
                    logI("NotLoading: +++++++++++++++")
                }
                //请求数据时返回了一个错误。
                is LoadState.Error -> {
                    dialog.cancel()
                    logI("Error: ======================")
                    toast("出现错误")
                    val errorLayoutBinding = DataBindingUtil.inflate<ErrorLayoutBinding>(
                        layoutInflater,
                        R.layout.error_layout,
                        rv.rootView as ViewGroup?,
                        true
                    )
                    errorLayoutBinding.retryBtn.setOnClickListener {
                        (rv.rootView as ViewGroup?)?.removeView(errorLayoutBinding.root)
                        adapter.refresh()
                    }
                }
            }
        }

        /***
         * LoadStateAdapter：可以添加页头/页脚，方便实现loadmore的样式
         * fun withLoadStateHeader(header: LoadStateAdapter<*> ) 头部添加状态适配器
         * fun withLoadStateFooter(footer: LoadStateAdapter<*> ) 底部添加状态适配器
         * fun withLoadStateHeaderAndFooter(header: LoadStateAdapter<>, footer: LoadStateAdapter<> ) 头尾都添加状态适配器
         * 谷歌出过一个 MergeAdapter，就是把多个RecyclerView.Adapter 合并成一个
         */
//        rv.adapter = adapter.withLoadStateHeaderAndFooter(
//            TestLoadStateAdapter(adapter),
//            HeaderLoadStateAdapter(adapter)
//        )
        //rv.adapter = adapter.withLoadStateHeader(ArticleHeaderLoadStateAdapter())
    }
}